package cuiyt.juc.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author cyt
 * @create 2020-04-29 21:26
 */

// 精准唤醒线程
public class demo04 {

    public static void main(String[] args) {
        data4 data = new data4();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.printA();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.printB();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.printC();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();

    }
}

//  A 执行完调用B，B执行完调用C，C执行完调用A
class data4 {

    // 创建一个锁
    Lock lock = new ReentrantLock();
    // 创建一个  Condition 对象来绑定到一个锁上面
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    // 1 = a , 2 = b , 3 = c

    int number = 1;

    public void printA() throws InterruptedException {
        lock.lock();
        try {
            while (number != 1) {
                condition1.await();
                // 等待
            }
            number = 2;
            System.out.println(Thread.currentThread().getName() + "->" + "AAAA");
            // 通知
            condition2.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }


    }

    public void printB() throws InterruptedException {

        lock.lock();

        try {
            while (number != 2) {
                condition2.await();
                // 等待
            }
            number = 3;
            System.out.println(Thread.currentThread().getName() + "->" + "BBBBB");
            // 通知
            condition3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() throws InterruptedException {
        lock.lock();
        try {
            while (number != 3) {
                condition3.await();
                // 等待
            }
            number = 1;
            System.out.println(Thread.currentThread().getName() + "->" + "BBBBB");
            // 通知
            condition1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
